<template>
  <div>
    <div class="queryBox">
      <el-input
        v-model.trim="searchModel.carNo"
        placeholder="请输入车牌号"
        @blur="queryData"
      />
      <el-input
        v-model.trim="searchModel.userMobile"
        placeholder="请输入订单手机号"
        @blur="queryData"
      />
      <el-input
        v-model.trim="searchModel.dealNo"
        placeholder="请输入交易订单号"
        @blur="queryData"
      />
    </div>
    <el-tabs @tab-click="switchTab">
      <el-tab-pane
        v-for="item in stateOptions"
        :key="item.value"
        :label="item.label"
        :name="item.value"
        stretch
      >
        <div
          class="content"
          v-infinite-scroll="slide"
          :infinite-scroll-distance="40"
          v-if="tableData.data.length > 0"
        >
          <div
            class="orderBox"
            v-for="data in tableData.data"
            :key="data.mainOrderId"
          >
            <span>
              {{ "订单手机号：" + data.userMobile }}
            </span>
            <span>
              {{ data.carNo ? "车牌号：" + data.carNo : "车牌号：" }}
            </span>
            <span>
              {{ "套餐名称：" + data.packName }}
            </span>
            <span>
              {{ "推广员姓名：" + data.agentName }}
            </span>
            <span>
              {{ "一级代理商ID：" + data.agentFirstMasterId }}
            </span>
            <span>
              {{ "推广员上级代理线：" + data.shangs }}
            </span>
            <span
              :style="{
                color: data.compositeState == 2 ? 'red' : 'black',
              }"
            >
              {{ "订单状态：" + judgeCompositeState(data) }}
            </span>
            <span :style="{ color: data.active == 1 ? '#21D86E' : 'black' }">
              {{ "激活状态：" + judgeActive(data) }}
            </span>
            <div class="divider"></div>
            <div
              v-if="
                data.compositeState &&
                refundOrNot(data) &&
                (data.price * 10 - data.refundTotal * 10) / 10 > 0
              "
              class="btnBox"
            >
              <div class="div-cell" v-if="data.payeeType === 1">
                <el-button
                  type="primary"
                  color="#ea5b24"
                  size="small"
                  @click="refundDialog(data, 0)"
                  v-if="pinia.isShow[125]"
                >
                  {{ "退款" }}
                </el-button>
                <el-button
                  type="primary"
                  color="#ea5b24"
                  size="small"
                  @click="refundDialog(data, 1)"
                  v-if="pinia.isShow[126]"
                >
                  {{ "强制退款" }}
                </el-button>
                <el-button
                  type="primary"
                  color="#ea5b24"
                  size="small"
                  @click="activateDialog(data)"
                  v-if="
                    pinia.isShow[127] &&
                    data.carNo &&
                    data.active == 0 &&
                    data.compositeState == 2
                  "
                >
                  {{ "激活状态更新" }}
                </el-button>
              </div>
              <el-button
                type="primary"
                color="#ea5b24"
                size="small"
                @click="cancelOrder(data)"
                v-if="pinia.isShow[128] && data.payeeType === 2"
              >
                {{ "取消订单" }}
              </el-button>
            </div>
          </div>
        </div>
        <div class="none-data" v-else>
          <image
            src="../../../assets/img/noData.png"
            class="none-data-image"
          ></image>
          <text class="none-data-text"> 没有查询到订单... </text>
          <div></div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 退款dialog -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款申请"
      center="true"
      modal="true"
      width="80%"
    >
      <el-form
        :model="refundParam"
        :rules="rules"
        ref="ruleFormRef"
        label-width="100"
        label-posit
        ion="right"
      >
        <el-form-item label="订单金额:">{{ refundParam.total }}</el-form-item>
        <el-form-item label="已退款总金额:">{{
          refundParam.refundTotal
        }}</el-form-item>
        <!-- <el-form-item label="已退款订单号:">
          <div class="form-span-inline">
            <span
              v-for="(item, index) in refundParam.refundOrderNos"
              :key="index"
            >
              {{ item }}
            </span>
          </div>
        </el-form-item> -->
        <el-form-item label="退款金额:" prop="refundAmt">
          <el-input-number
            v-model="refundParam.refundAmt"
            :precision="2"
            :max="(refundParam.total * 10 - refundParam.refundTotal * 10) / 10"
            :min="0"
            :controls="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="退款原因:" prop="reason">
          <el-input
            v-model.trim="refundParam.reason"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="refundDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="refundReq(ruleFormRef)"
            color="#ea5b24"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 激活更新dialog -->
    <el-dialog
      v-model="activateDialogVisible"
      title="激活更新"
      center="true"
      modal="true"
      width="80%"
    >
      <el-form :model="activateParam">
        <el-form-item label="车牌号:">{{ activateParam.carNo }}</el-form-item>
        <el-form-item label="套餐系列:">{{
          activateParam.series
        }}</el-form-item>
        <el-form-item label="审核类型:">
          <el-select v-model="activateParam.state" placeholder="请选择">
            <el-option label="未激活" value="0" />
            <el-option label="已激活" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="激活日期:">
          <el-date-picker
            v-model="activateParam.activeTime"
            type="datetime"
            placeholder="请选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="activateDialogVisible = false">取消</el-button>
          <el-button type="primary" color="#ea5b24" @click="activateUpdate()"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import {
  findVipOrderApi,
  refundVipOrderApi,
  activeUpdateApi,
  cancelVipOrderApi,
  queryRefundEtcApi,
} from "../../../api/index";
import { formatDateTime } from "../../../utils/formatDateTime";
import { usePermissStore } from "../../../store/permiss";
const pinia = usePermissStore();

// 分页列表数据
let tableData: any = reactive({ data: [] });
const totalNum = ref(0);
let active = ref(false);
const page = ref(1);
const size = 6;

// 退款dialog控制
const refundDialogVisible = ref(false);
// 激活更新dialog控制
const activateDialogVisible = ref(false);
// 退款参数
const refundParam = reactive({
  mainOrderId: null, //主订单id
  total: null, //支付金额
  refundTotal: null, //已退款总金额
  refundOrderNos: null, //已退款订单号
  refundAmt: null, //退款金额
  reason: null, //退款原因
  refundType: null, //退款or强制退款
});
// 激活更新参数
const activateParam = reactive({
  etcOrderId: null,
  carNo: null,
  series: null,
  state: null,
  activeTime: null,
});

// 汇总数据
const summaryData: any = reactive({
  debitCount: null, //扣款总条数
  debitSum: null, //扣款总金额
  refundCount: null, //退款总条数
  refundSum: null, //退款总金额
  activeCount: null, //激活总条数
  activeSum: null, //激活总金额
});

// 搜索模型
const searchModel: any = reactive({
  carNo: null,
  compositeState: null,
  dealNo: null,
  //   payState: null,
  //   lastRefundState: null,
  userId: null,
  series: null,
  packName: null,
  agentId: null,
  userName: null,
  carType: null,
  agentFirstMasterId: null,
  active: null,
  createDate: null,
  startTime: null,
  endTime: null,
  activeTime: null,
  activeEndTime: null,
  orderSn: null,
  userMobile: null,
  payType: null,
  deviceNumber: null,
  page: page,
  size: size,
});

// 修改车牌号模型
const carNoModel: any = reactive({
  newCarNo: null,
  oldCarNo: null,
  etcOrderId: null,
});

//表单校验
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  reason: [{ required: true, message: "请输入退款原因", trigger: "blur" }],
  refundTotal: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
  refundAmt: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
});

// 状态枚举
const stateOptions: any = reactive([
  { value: null, label: "全部" },
  { value: "1", label: "未支付" },
  { value: "7", label: "支付中" },
  { value: "2", label: "已支付" },
  { value: "8", label: "支付失败" },
  { value: "4", label: "退款中" },
  { value: "5", label: "退款成功" },
  { value: "6", label: "退款失败" },
  { value: "9", label: "已取消" },
]);

// 判断状态显示
const judgeCompositeState = (row) => {
  switch (row.compositeState) {
    case 1:
      return "未支付";
    case 2:
      return "已支付";
    case 4:
      return "退款中";
    case 5:
      return "退款成功";
    case 6:
      return "退款失败";
    case 7:
      return "支付中";
    case 8:
      return "支付失败";
    case 9:
      return "已取消";
    default:
      return "";
  }
};

// 判断支付方式显示
const judgePayType = (row) => {
  let str = "";
  pinia.allDic?.order_summary_pay_channel?.dicList.forEach((item) => {
    if (item.dicValue == row.payType) {
      str = item.dicName;
      return;
    }
  });
  return str;
};

// 判断激活状态显示
const judgeActive = (row) => {
  switch (row.active) {
    case 0:
      return "未激活";
    case 1:
      return "已激活";
    default:
      return "";
  }
};

// 判断颜色显示
const judgeColor = (row) => {
  switch (row.carColor) {
    case 1:
      return "黄色";
    case 2:
      return "蓝色";
    case 3:
      return "渐变绿色";
    case 4:
      return "黄绿双";
    default:
      return "";
  }
};

// 翻页
let flipData = reactive({
  page: page,
  size: size,
});
const handleCurrentChange = (val: number) => {
  page.value = val;
  flipData.page = page.value;
  findOrder(flipData);
};

// 判断是否可退款
const refundOrNot = (row) => {
  const condition = [2, 4, 5, 6];
  if (condition.includes(row.compositeState)) {
    return true;
  } else {
    return false;
  }
};

// 退款dialog
const refundDialog = (row, refundType) => {
  if (
    (row.series == "Y系列" || row.series == "K系列") &&
    row.active == 1 &&
    refundType == 0
  ) {
    ElMessage({
      message: "不允许退款,请走强制退款流程.",
      type: "warning",
      offset: window.screen.height / 4,
    });
    return;
  }
  ruleFormRef.value ? ruleFormRef.value.clearValidate() : false;
  Object.keys(refundParam).forEach((key) => (refundParam[key] = null));
  refundParam.mainOrderId = row.mainOrderId;
  refundDialogVisible.value = true;
  refundParam.refundType = refundType;
  refundParam.reason = "";

  findRefundHistory(refundParam.mainOrderId);
};
// 激活更新dialog
const activateDialog = (row) => {
  Object.keys(activateParam).forEach((key) => (activateParam[key] = null));
  activateDialogVisible.value = true;
  activateParam.etcOrderId = row.etcOrderId;
  activateParam.carNo = row.carNo;
  activateParam.series = row.series;
};
// 搜索扣款订单
const searchOrder = () => {
  searchParmSearch();
  findOrder(searchModel);
  flipData = JSON.parse(JSON.stringify(searchModel));
};

// 查询扣款订单
const findOrder = (searchModel) => {
  findVipOrderApi(searchModel).then((res) => {
    if (res.data.code === 2000 && res.data.data.pageData.items) {
      tableData.data = [...tableData.data, ...res.data.data.pageData.items];
    } else {
      ElMessage({
        message: "查询失败.",
        type: "error",
        offset: window.screen.height / 4,
      });
    }
  });
};

// 搜索参数检查
const searchParmSearch = () => {
  Object.keys(searchModel).forEach((key) => {
    if (searchModel[key] === "" || searchModel[key] === undefined) {
      searchModel[key] = null;
    }
  });
};

//查询退款历史信息
const findRefundHistory = (orderId) => {
  queryRefundEtcApi(orderId).then((res) => {
    if (res.data.code === 2000) {
      refundParam.total = res.data.data.total;
      refundParam.refundTotal = res.data.data.refundTotal;
      refundParam.refundOrderNos = res.data.data.refundOrderNos;
    } else {
      ElMessage({
        message: "查询失败.",
        type: "error",
        offset: window.screen.height / 4,
      });
    }
  });
};

// 退款申请
const refundReq = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (refundParam.refundAmt <= 0) {
        ElMessage({
          message: "退款金额必须大于0.",
          type: "error",
          offset: window.screen.height / 4,
        });
        return;
      }
      refundVipOrderApi(refundParam).then((res) => {
        if (res.data.code === 2000) {
          findOrder(searchModel);
          ElMessage({
            message: "申请成功.",
            type: "success",
            offset: window.screen.height / 4,
          });
        } else {
          switch (res.data.code) {
            case 5008:
              ElMessage({
                message: "申请失败:请输入退款金额.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            case 5000:
              ElMessage({
                message: "申请失败:当前订单正在退款中，请勿频繁操作.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            case 5206:
              ElMessage({
                message: "退款失败，订单已激活，请进行强制退款.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            case 5205:
              ElMessage({
                message: "易宝-退款失败.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            case 5207:
              ElMessage({
                message: "易宝-退款失败，未找到对应的vip套餐.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            case 5208:
              ElMessage({
                message: "退款失败，支付渠道错误.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            case 52011:
              ElMessage({
                message: "退款失败，累计退款金额大于支付金额.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
            default:
              ElMessage({
                message: "申请失败.",
                type: "error",
                offset: window.screen.height / 4,
              });
              break;
          }
        }
        refundDialogVisible.value = false;
      });
    } else {
      return false;
    }
  });
};

// 激活更新
const activateUpdate = () => {
  if (activateParam.state == null) {
    ElMessage({
      message: "请选择审核类型.",
      type: "warning",
      offset: window.screen.height / 4,
    });
    return;
  }
  if (activateParam.activeTime == null) {
    ElMessage({
      message: "请输入激活日期.",
      type: "warning",
      offset: window.screen.height / 4,
    });
    return;
  }
  activeUpdateApi(activateParam).then((res) => {
    if (res.data.code === 2000) {
      findOrder(searchModel);
      ElMessage({
        message: "激活成功.",
        type: "success",
        offset: window.screen.height / 4,
      });
    } else {
      ElMessage({
        message: "激活失败.",
        type: "error",
        offset: window.screen.height / 4,
      });
    }
    activateDialogVisible.value = false;
  });
};

//取消订单
const cancelOrder = (row) => {
  ElMessageBox.confirm("是否确认取消订单?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    cancelVipOrderApi(row.mainOrderId).then((res) => {
      if (res.data.code === 2000) {
        ElMessage({
          message: "取消成功.",
          type: "success",
          offset: window.screen.height / 4,
        });
        findOrder(searchModel);
      } else {
        ElMessage({
          message: "取消失败.",
          type: "error",
          offset: window.screen.height / 4,
        });
      }
    });
  });
};

function switchTab(val) {
  tableData.data.length = 0;
  searchModel.compositeState = val.props.name;
  page.value = 1;
  searchOrder();
}

const slide = pinia.debounce(() => {
  if (tableData.data.length != 0) {
    page.value += 1;
    searchOrder();
  }
});

function queryData() {
  tableData.data.length = 0;
  page.value = 1;
  searchOrder();
}

onMounted(() => {
  findOrder(searchModel);
});
</script>
<style scoped lang="less">
.queryBox {
  padding: 0 20px;
  .el-input {
    margin-top: 10px;
  }
}
.content {
  box-sizing: border-box;
  width: 100%;
  max-height: 100vh;
  overflow-y: auto;
  padding: 10px 18px;
  .orderBox {
    box-sizing: border-box;
    width: 100%;
    background-color: #fff;
    border-radius: 18px;
    box-shadow: 3px 4px 6px 0px rgba(0, 0, 0, 0.1);
    margin-bottom: 15px;
    padding: 12px;
    display: flex;
    flex-direction: column;

    span {
      padding: 3px 0;
      color: #3c3c3c;
      font-weight: 400;
      font-size: 14px;
    }
    .divider {
      width: 100%;
      border-bottom: 1px solid #e6e6e6;
      margin: 10px 0;
    }
    .btnBox {
      display: flex;
      justify-content: flex-end;
    }
  }
}

.none-data {
  display: flex;
  justify-content: center;
  width: 380rpx;
  height: 380rpx;
  flex-direction: column;
  margin: 0 auto;
  position: absolute;
  top: 35%;
  left: 50%;
  transform: translate(-50%, -50%);
  opacity: 0.6;

  .none-data-image {
    height: 100%;
    width: 100%;
    background-size: 100%;
  }

  .none-data-text {
    margin-top: 8rpx;
    text-align: center;
    color: #666666;
    font-weight: 400;
    font-size: 28rpx;
  }
}

.el-tabs--card {
  height: calc(100vh - 180px);
  /* overflow-y: auto; */
}
.el-tab-pane {
  height: calc(100vh - 180px);
  overflow-y: auto;
}
</style>
